package eerbaar.shared.persist.internal.lib;

import eerbaar.memory.IMemory;
import eerbaar.memory.MemoryFactory;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.persist.node.NodePersister;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;


public class MemoryPersister implements IPersister<IMemory> {

    private IMemory target;

    public MemoryPersister() {
        //
    }

    public MemoryPersister(IMemory wrapper) {
        this.target = wrapper;
    }

    public MemoryPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IMemory> getRegistertedInterface() {

        return IMemory.class;
    }

    @Override
    public NodePersister[] getSavableChildren() {

        NodePersister p = new NodePersister(this.target.getRoot());
        NodePersister[] a = new NodePersister[] { p };
        return a;
    }

    @Override
    public String getSavableName() {

        return "memory";
    }

    @Override
    public IMemory getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> savable) {
        return false;
    }

    @Override
    public IMemory load(INode node) {
        assert (node != null);

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);
        IPersister<INode> p = service.getPersister(INode.class);
        INode root = p.load(node.getChild(0));

        return MemoryFactory.create(root);
    }

    @Override
    public void saveAttributes(INode node) {
        //
    }

    @Override
    public void setTarget(IMemory obj) {
        this.target = obj;
    }

}
